package com.central.post.mq

import org.apache.rocketmq.common.message.MessageConst
import org.springframework.cloud.stream.annotation.EnableBinding
import org.springframework.cloud.stream.annotation.Output
import org.springframework.messaging.Message
import org.springframework.messaging.MessageChannel
import org.springframework.messaging.MessageHeaders
import org.springframework.messaging.support.MessageBuilder
import org.springframework.util.MimeTypeUtils

/**
 * @author  fly
 * @date  2021/5/28 18:09
 * @version 1.0
 */
const val integral = "post_integral_service"

const val comment = "comment_service"

const val subscribe_post = "wx_post_subscribe_service"

const val subscribe_new_good = "wx_new_good_subscribe_service"

@EnableBinding(PostSink::class)
open class PostMqConfig

interface PostSink {

    /**
     * 发送到积分服务
     */
    @Output(integral)
    fun integralProduct(): MessageChannel

    /**
     * 发送到评论服务
     */
    @Output(comment)
    fun commentProduct(): MessageChannel


    /**
     * 帖子发送到微信订阅服务
     */
    @Output(subscribe_post)
    fun subscribePostProduct(): MessageChannel

    /**
     * 上新发送到微信订阅服务
     */
    @Output(subscribe_new_good)
    fun subscribeNewGoodProduct(): MessageChannel
}

fun <T> T.toMessage(tag: String?): Message<T> =  MessageBuilder.withPayload(this)
    .setHeader(MessageConst.PROPERTY_TAGS, tag)
    .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
    .build()

/**
 * 发送积分服务
 */
fun <T> PostSink.sendIntegralMes(msg: T, tag: String?) = this.integralProduct().send(msg.toMessage(tag))

/**
 * 发送到评论服务
 */
fun <T> PostSink.sendMessage(msg: T, tag: String?) = this.commentProduct().send(msg.toMessage(tag))

/**
 * 发送到帖子微信订阅服务
 */
fun <T> PostSink.sendPostSubscribe(msg: T, tag: String?) = this.subscribePostProduct().send(msg.toMessage(tag))

/**
 * 发送到上新微信订阅服务
 */
fun <T> PostSink.sendNewGoodSubscribe(msg: T, tag: String?) = this.subscribeNewGoodProduct().send(msg.toMessage(tag))
